import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Layout from '@/components/Layout.vue'
import LoginView from '@/views/LoginView.vue'

// 基础路由（不需要权限的路由）
const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      }
    ]
  }
]

// 动态获取组件
function getComponentByPath(path) {
  try {
    // 处理路径，去掉开头的斜杠
    const cleanPath = path.startsWith('/') ? path.substring(1) : path
    // 特殊情况：dashboard 直接返回
    if (cleanPath === 'dashboard') {
      return () => import('@/views/Dashboard.vue')
    }
    
    // 解析路径结构
    const pathParts = cleanPath.split('/')
    if (pathParts.length === 1) {
      // 一级菜单目录 - 这些通常不需要组件
      return null
    } else if (pathParts.length >= 2) {
      // 二级及以上菜单，直接使用URL路径结构映射到views目录
      const [category, page] = pathParts
      
      // 将页面名转换为组件名（首字母大写）
      let componentName = page.charAt(0).toUpperCase() + page.slice(1)
      
      // 预定义的组件映射表，避免动态路径解析问题

      // const componentMap = {
      //   'system/User': () => import('@/views/system/User.vue'),
      //   'system/Role': () => import('@/views/system/Role.vue'),
      //   'system/Menu': () => import('@/views/system/Menu.vue'),
      //   'system/Config': () => import('@/views/system/Config.vue'),
      //   'skyeye/IpConfig': () => import('@/views/skyeye/IpConfig.vue'),
      //   'skyeye/Variable': () => import('@/views/skyeye/Variable.vue'),
      //   'skyeyedata/SegmentDetail': () => import('@/views/skyeyedata/SegmentDetail.vue')
      // }
      const componentMap={}
      const componentKey = `${category}/${componentName}`
      // 动态导入组件
      try {
        return () => import(`@/views/${category}/${componentName}.vue`)
      } catch (error) {
        console.warn(`动态导入组件失败: @/views/${category}/${componentName}.vue`, error)
        return null
      }
    }
    return null
  } catch (error) {
    console.error(`加载组件失败: ${path}`, error)
    return null
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})

// 生成动态路由
function generateRoutes(menus) {
  const routes = []
  
  function processMenu(menu) {
    // 只为有实际页面组件的菜单生成路由（二级菜单或特殊的一级页面如dashboard）
    if (menu.path && !menu.children) {
      // 这是一个叶子节点菜单，尝试生成路由
      const component = getComponentByPath(menu.path)
      console.log('动态路由：',component)
      if (component) {
        const routePath = menu.path.startsWith('/') ? menu.path.substring(1) : menu.path
        routes.push({
          path: '/' + routePath,
          name: routePath.replace(/\//g, '-'),
          component: component,
          meta: { 
            title: menu.name,
            icon: menu.icon || '',
            id: menu.id,
            path: menu.path
          }
        })
      }
    }
    
    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        processMenu(child)
      })
    }
  }
  
  menus.forEach(menu => processMenu(menu))
  return routes
}

// 添加动态路由
function addDynamicRoutes(menus) {
  const dynamicRoutes = generateRoutes(menus)
  console.log('dynamicRoutes', dynamicRoutes)
  // 将动态路由添加为 Layout 的子路由
  dynamicRoutes.forEach(route => {
    // 移除路径开头的 '/' 因为这些是子路由
    const childRoute = {
      ...route,
      path: route.path.startsWith('/') ? route.path.substring(1) : route.path
    }
    router.addRoute('layout', childRoute)
  })
  
  console.log('动态路由已添加:', dynamicRoutes.map(r => r.path))
}

// 路由守卫
router.beforeEach(async (to) => {
  const authStore = useAuthStore()
  console.log('路由守卫:', { path: to.path, isAuth: authStore.isAuthenticated, menuCount: authStore.userMenus.length })
  
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    return '/login'
  }
  
  if (to.path === '/login' && authStore.isAuthenticated) {
    return '/'
  }
  
  // 如果已登录但菜单为空（刷新页面时可能发生）
  if (authStore.isAuthenticated && authStore.userMenus.length === 0) {
    try {
      console.log('正在加载用户信息和菜单...')
      const result = await authStore.getCurrentUser()
      console.log('加载结果:', result, '菜单数量:', authStore.userMenus.length)
      
      if (result.success && authStore.userMenus.length > 0) {
        addDynamicRoutes(authStore.userMenus)
        // 如果当前访问的不是首页，重新路由到目标页面
        if (to.path !== '/' && to.path !== '/dashboard') {
          return to.fullPath
        }
      }
    } catch (error) {
      console.error('加载用户信息失败:', error)
      authStore.logout()
      return '/login'
    }
  }
})

export default router
